package com.example.yamba;

import java.util.List;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.util.Log;

public class UpdaterService extends Service {

	static final String TAG = "UpdaterService";
	
	static final int DELAY = 10000; // 60000 = 1 minute
	private boolean runFlag = false;
	private Updater updater;
	private YambaApplication1 yamba;

	SQLiteDatabase db;
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		this.updater = new Updater();
		this.yamba = ((YambaApplication1)getApplication());

		
		Log.d(TAG,"onCreate");
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.runFlag = false;
		// this.updater.stop(); -- should stop cleanly because the runFlag is set to false
		this.updater.interrupt();
		this.updater = null;
		yamba.setServiceRunning(false);
		Log.d(TAG,"onDestroy");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		super.onStartCommand(intent, flags, startId);
		this.runFlag = true;
		this.updater.start();
		Log.d(TAG,"onStartCommand");
		yamba.setServiceRunning(true);
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	private class Updater extends Thread
	{
		
		List<Twitter.Status> timeline;
		
		public Updater()
		{
			super("UpdaterService-Updater");
		}

		@Override
		public void run() {
			
			super.run();
			
			UpdaterService updaterService = UpdaterService.this;
			while(updaterService.runFlag)
			{
				Log.d(TAG,"Running Background thread");
				
				try
				{
					// do the work
				
					YambaApplication1 yamba = (YambaApplication1)updaterService.getApplication();
					int newUpdates = yamba.fetchStatusUpdates();
					
					if (newUpdates > 0)
						Log.d(TAG,"We have new Updates");							
					
					Thread.sleep(DELAY);
				}
				catch(InterruptedException e)
				{
					updaterService.runFlag = false;
				}
				
		
			}
			
			Log.d(TAG,"Updater stopping");
		}

		@Override
		public void interrupt() {
			// TODO Auto-generated method stub
			super.interrupt();
			Log.d(TAG,"Updater interrupt");
		}
		
		
		
	
	}

}
